/**
 * 明细分类账建账 - 录入建账数据
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0002.Init.DetailEditForm", {
  extend: "PSI.AFX.Form.EditForm",

  config: {
    companyId: null,
    companyName: null,
  },

  /**
   * @override
   */
  initComponent() {
    const me = this;

    const buttons = [];
    const btn = {
      text: "保存并继续录入下一条建账数据",
      ...PSI.Const.BTN_STYLE,
      formBind: true,
      handler() {
        me._onOK(true);
      },
      scope: me
    };

    buttons.push(btn);

    buttons.push({
      text: "保存",
      ...PSI.Const.BTN_STYLE,
      formBind: true,
      iconCls: "PSI-button-ok",
      handler() {
        me._onOK(false);
      },
      scope: me
    });

    buttons.push({
      text: "取消",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.close();
      },
      scope: me
    });

    const t = "录入明细分类账建账会计期间期末数据";
    const logoHtml = me.genLogoHtml(null, t);

    const width1 = 600;
    const width2 = 295;

    PCL.apply(me, {
      header: {
        title: me.formatTitle(PSI.Const.PROD_NAME),
        height: 40
      },
      width: 650,
      height: 550,
      layout: "border",
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
        close: {
          fn: me._onWndClose,
          scope: me
        }
      },
      items: [{
        region: "north",
        height: 70,
        border: 0,
        html: logoHtml
      }, {
        region: "center",
        border: 0,
        id: me.buildId(me, "editForm"),
        xtype: "form",
        layout: {
          type: "table",
          columns: 2,
          tableAttrs: PSI.Const.TABLE_LAYOUT,
        },
        height: "100%",
        bodyPadding: 5,
        defaultType: 'textfield',
        fieldDefaults: {
          labelWidth: 70,
          labelAlign: "right",
          labelSeparator: "",
          msgTarget: 'side',
          width: width2,
          margin: "5"
        },
        items: [{
          id: me.buildId(me, "hiddenOrg"),
          xtype: "hidden",
          value: me.getCompanyId(),
        }, {
          xtype: "displayfield",
          fieldLabel: "组织机构",
          value: me.toFieldNoteText(me.getCompanyName()),
          width: width1,
          colspan: 2,
        }, {
          id: me.buildId(me, "editDT"),
          fieldLabel: "期末日期",
          allowBlank: false,
          blankText: "没有输入期末日期",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          xtype: "datefield",
          format: "Y-m-d",
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          },
        }, {
          id: me.buildId(me, "editSubject"),
          fieldLabel: "科目",
          allowBlank: false,
          blankText: "没有输入科目",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          xtype: "psi_subjectfield",
          editOrgId: me.buildId(me, "hiddenOrg"),
          callbackFunc: me._subjectEditorCallbackFunc,
          callbackScope: me,
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          },
        }, {
          id: me.buildId(me, "editSubjectName"),
          fieldLabel: "科目名称",
          xtype: "textfield",
          readOnly: true,
          colspan: 2,
          width: width1,
        }, {
          id: me.buildId(me, "editMoney"),
          fieldLabel: "期末余额",
          xtype: "numberfield",
          allowDecimals: true,
          decimalPrecision: 2,
          hideTrigger: true,
          keyNavEnabled: false,
          mouseWheelEnabled: false,
          width: width2,
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          },
        }, {
          xtype: "displayfield",
          value: "<span style='color:#8c8c8c;font-size:12px'>期末余额录入0，则表示删除对应的明细分类账建账记录</span>",
          width: width1,
        }, {
          id: me.buildId(me, "editBalanceDir"),
          fieldLabel: "余额方向",
          xtype: "combobox",
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: [[1, "借方"], [2, "贷方"],]
          }),
          valueField: "id",
          displayFIeld: "text",
          queryMode: "local",
          editable: false,
          width: width2,
          listeners: {
            specialkey: {
              fn: me._onLastEditSpecialKey,
              scope: me
            }
          },
          colspan: 2,
        }, {
          id: me.buildId(me, "fsFmtEx"),
          xtype: "fieldset",
          title: "<span style='color:gray;font-size:14px;'>账簿扩展项</span>",
          defaults: { anchor: '100%', labelWidth: 32 },
          columnWidth: 0.5,
          layout: 'anchor',
          colspan: 2,
          width: width1 + 10,
          layout: 'anchor',
          items: [
            { xtype: "textfield", fieldLabel: "", value: "没有扩展项", readOnly: true },
          ]
        }
        ],
        buttons,
      }]
    });

    me.callParent(arguments);

    me.editDT = PCL.getCmp(me.buildId(me, "editDT"));
    me.editSubject = PCL.getCmp(me.buildId(me, "editSubject"));
    me.editSubjectName = PCL.getCmp(me.buildId(me, "editSubjectName"));
    me.editMoney = PCL.getCmp(me.buildId(me, "editMoney"));
    me.editBalanceDir = PCL.getCmp(me.buildId(me, "editBalanceDir"));

    me.fsFmtEx = PCL.getCmp(me.buildId(me, "fsFmtEx"));

    me.editForm = PCL.getCmp(me.buildId(me, "editForm"));

    // AFX
    me.__editorList = [me.editDT, me.editSubject, me.editMoney, me.editBalanceDir];
  },

  /**
   * @private
   */
  _subjectEditorCallbackFunc(data) {
    const me = this;

    // 查询账簿扩展项
    me.queryFmtEx(data.get("code"));
  },

  /**
   * @private
   */
  queryFmtEx(subjectCode) {
    const me = this;

    const companyId = me.getCompanyId();

    me.ajax({
      url: me.URL("SLN0002/Init/queryFmtEx"),
      params: {
        companyId,
        subjectCode,
      },
      callback(opt, success, response) {
        if (success) {
          const data = me.decodeJSON(response.responseText);

          me.editSubjectName.setValue(data.subjectName);
          const dir = parseInt(data.balanceDir);
          me.editBalanceDir.setReadOnly(false);

          if (dir == 1 || dir == 2) {
            me.editBalanceDir.setReadOnly(true);
            me.editBalanceDir.setValue(dir);
          }

          me._fmtData = data.fmtList;
          me.createInputsFromFmtCols();
        }
      },
    });
  },

  /**
   * @private
   */
  createInputsFromFmtCols() {
    const me = this;
    if (!me._fmtData) {
      return;
    }

    me.fsFmtEx.removeAll();
    if (me._fmtData.length == 0) {
      me.fsFmtEx.add({
        xtype: "textfield", fieldLabel: "",
        value: "没有扩展项", readOnly: true
      });
    }

    me._fmtData.forEach((col, index) => {
      const input = {
        readOnly: me._readonly,
        _index: index,
        _colId: col.id, // 对应t_acc_fmt_cols表的id字段
        value: col.value,
        xtype: col.voucherInputXtype,
        beforeLabelTextTpl: PSI.Const.REQUIRED,
        fieldLabel: col.caption,
        labelAlign: "right",
        labelSeparator: "",
        labelWidth: 70,
        listeners: {
          specialkey: {
            fn: me._onFmtEditSpecialkey,
            scope: me
          },
        },
      };

      // 日期
      if (col.voucherInputXtype == "datefield") {
        PCL.apply(input, {
          format: "Y-m-d",
          // value: new Date(),
        });
      }

      // 数值
      if (col.voucherInputXtype == "numberfield") {
        PCL.apply(input, {
          hideTrigger: true,
          minValue: 0,
          allowDecimals: col.fieldDec > 0,
          decimalPrecision: col.fieldDec,
          hideTrigger: true,
          keyNavEnabled: false,
          mouseWheelEnabled: false,
        });
      }

      // 码表录入
      if (col.voucherInputXtype == "psi_codetable_voucherfield") {
        PCL.apply(input, {
          fid: col.fid,
          isCodeTable: true,
          initIdValue: col.codeId,
          companyIdFuncCallback() {
            return me.getCompanyId();
          },
          companyIdFuncCallbackScope: me,
        });
      }

      me.fsFmtEx.add(input);
    });
  },

  /**
   * @private
   */
  _onFmtEditSpecialkey(field, e) {
    const me = this;

    if (e.getKey() === e.ENTER) {
      // 同步数据
      const value = field.getValue();
      if (!value) {
        me.showInfo(`没有输入账簿扩展项 <span style='color:red'>${field.fieldLabel}</span> 的数据`, () => {
          field.focus();
        });
        return;
      }

      // 处理跳转
      const input = me.fsFmtEx.getComponent(field._index + 1);
      if (input) {
        me.setFocusAndCursorPosToLast(input);
      } else {
        // 最后一个input了，提交数据
        me._onOK(true);
      }
    }
  },

  /**
   * 保存
   * 
   * @private
   */
  _onOK(thenAdd) {
    const me = this;

    if (!me.checkData()) {
      return;
    }

    PCL.getBody().mask("正在保存中...");
    me.ajax({
      url: me.URL("SLN0002/Init/editAccDetailInitRecord"),
      params: {
        jsonStr: me.getSaveData(),
      },
      callback(options, success, response) {
        PCL.getBody().unmask();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          if (data.success) {
            if (thenAdd) {
              me.clearEdit();
              me.tip("成功保存数据", true);
              me.editSubject.focus();
            } else {
              me.close();
            }

            const pf = me.getParentForm();
            if (pf && pf.refreshMainGrid) {
              pf.refreshMainGrid.apply(pf);
            }
          } else {
            me.showInfo(data.msg, () => {
              me.editDT.focus();
            });
          }
        } else {
          me.showInfo("网络错误");
        }
      }
    });
  },

  /**
   * @private
   */
  _onLastEditSpecialKey(field, e) {
    const me = this;

    if (e.getKey() == e.ENTER) {
      // ComboBox的下拉框出现的时候，回车是选中下拉框中相应的条码
      if (field.isExpanded) {
        return;
      }

      if (me._fmtData?.length > 0) {
        // 有分录扩展项
        const input = me.fsFmtEx.getComponent(0);
        input.focus();
      } else {
        me._onOK(true);

      }
    }
  },

  /**
   * @private
   */
  clearEdit() {
    const me = this;

    me._fmtData = [];

    me.editSubject.clearIdValue();
    me.editSubject.clearInvalid();;
    me.editSubjectName.setValue(null);
    me.editMoney.setValue(null);

    me.fsFmtEx.removeAll();
    me.fsFmtEx.add({
      xtype: "textfield", fieldLabel: "",
      value: "没有扩展项", readOnly: true
    });
  },

  /**
   * @private
   */
  _onWndClose() {
    const me = this;

    // AFX
    PCL.get(window).un('beforeunload', me.__onWindowBeforeUnload);

    PCL.WindowManager.hideAll();
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    const companyId = me.getCompanyId();

    // AFX
    PCL.get(window).on('beforeunload', me.__onWindowBeforeUnload);

    const el = me.getEl() || PCL.getBody();
    el.mask(PSI.Const.LOADING);
    const r = {
      url: me.URL("SLN0002/Init/queryAccInitYearAndMonth"),
      params: {
        companyId,
      },
      callback(options, success, response) {
        el.unmask();

        if (success) {
          const data = me.decodeJSON(response.responseText);

          me.editDT.setValue(data.dt);

          me.setFocusAndCursorPosToLast(me.editDT);
        } else {
          me.showInfo("网络错误");
        }
      }
    };

    me.ajax(r);
  },

  /**
   * @private
   */
  getSaveData() {
    const me = this;

    // 账簿扩展项
    const ex = [];
    me._fmtData.forEach((col, index) => {
      const input = me.fsFmtEx.getComponent(index);
      const item = {
        id: col.id,
        value: input.getValue()
      };
      if (col.voucherInputXtype == "psi_codetable_voucherfield") {
        PCL.apply(item, {
          codeId: input.getIdValue(),
          codeValue: input.getCodeValue(),
          nameValue: input.getNameValue(),
        });
      }

      ex.push(item);
    });

    const result = {
      companyId: me.getCompanyId(),
      dt: PCL.Date.format(me.editDT.getValue(), "Y-m-d"),
      subjectCode: me.editSubject.getValue(),
      money: me.editMoney.getValue(),
      balanceDir: me.editBalanceDir.getValue(),
      ex,
    };

    return me.encodeJSON(result);
  },

  /**
   * 检查数据是否录入完整
   * 
   * @private
   */
  checkData() {
    const me = this;

    let v = me.editDT.getValue();
    if (!v) {
      me.showInfo("没有录入期末日期", () => {
        me.editDT.focus();
      });

      return false;
    }

    v = me.editSubject.getValue();
    if (!v) {
      me.showInfo("没有录入科目", () => {
        me.editSubject.focus();
      });

      return false;
    }

    v = me.editMoney.getValue();
    if (v === null) {
      // v === 0 被允许录入
      me.showInfo("没有录入期末余额", () => {
        me.editMoney.focus();
      });

      return false;
    }

    // 账簿扩展项
    let result = true;
    me._fmtData.forEach((col, index) => {
      if (result) {
        const input = me.fsFmtEx.getComponent(index);
        v = input.getValue();
        if (!v) {
          me.showInfo(`没有录入[${col.caption}]的数据`, () => {
            input.focus();
          })
          result = false;
        }
      }
    });

    return result;
  },
});
